package sdk

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"

	"github.com/yourusername/virt-manager-go/internal/models"
)

// NetworkClient 提供网络管理相关的 API 操作
type NetworkClient struct {
	client *APIClient
}

// NewNetworkClient 创建新的网络客户端
func NewNetworkClient(client *APIClient) *NetworkClient {
	return &NetworkClient{
		client: client,
	}
}

// ListNetworks 列出指定连接的所有网络
func (n *NetworkClient) ListNetworks(ctx context.Context, connectionID string) ([]models.NetworkSummary, error) {
	// 构建带查询参数的URL
	u := "/api/v1/networks"
	if connectionID != "" {
		u = fmt.Sprintf("/api/v1/networks?connection=%s", url.QueryEscape(connectionID))
	}

	data, err := n.client.Get(ctx, u)
	if err != nil {
		return nil, fmt.Errorf("failed to list networks for connection %s: %w", connectionID, err)
	}

	// API 返回的是包装格式 {"networks": [...], "count": n}
	var response struct {
		Networks []models.NetworkSummary `json:"networks"`
		Count    int                     `json:"count"`
	}
	if err := json.Unmarshal(data, &response); err != nil {
		return nil, fmt.Errorf("failed to unmarshal networks response: %w", err)
	}

	return response.Networks, nil
}

// GetNetwork 获取指定连接的网络详情
func (n *NetworkClient) GetNetwork(ctx context.Context, connectionID, name string) (*models.NetworkDetail, error) {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/network?connection=%s&name=%s", url.QueryEscape(connectionID), url.QueryEscape(name))

	data, err := n.client.Get(ctx, u)
	if err != nil {
		return nil, fmt.Errorf("failed to get network for connection %s: %w", connectionID, err)
	}

	var network models.NetworkDetail
	if err := json.Unmarshal(data, &network); err != nil {
		return nil, fmt.Errorf("failed to unmarshal network: %w", err)
	}

	return &network, nil
}

// CreateNetwork 在指定连接创建新网络
func (n *NetworkClient) CreateNetwork(ctx context.Context, connectionID string, xmlConfig string) error {
	// 构建带查询参数的URL
	u := "/api/v1/networks"
	if connectionID != "" {
		u = fmt.Sprintf("/api/v1/networks?connection=%s", url.QueryEscape(connectionID))
	}

	req := map[string]string{
		"xml_config": xmlConfig,
	}
	_, err := n.client.Post(ctx, u, req)
	if err != nil {
		return fmt.Errorf("failed to create network for connection %s: %w", connectionID, err)
	}
	return nil
}

// DeleteNetwork 删除指定连接的网络
func (n *NetworkClient) DeleteNetwork(ctx context.Context, connectionID, name string) error {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/network?connection=%s&name=%s", url.QueryEscape(connectionID), url.QueryEscape(name))

	_, err := n.client.Delete(ctx, u)
	if err != nil {
		return fmt.Errorf("failed to delete network for connection %s: %w", connectionID, err)
	}
	return nil
}

// StartNetwork 启动指定连接的网络
func (n *NetworkClient) StartNetwork(ctx context.Context, connectionID, name string) error {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/network/start?connection=%s&name=%s", url.QueryEscape(connectionID), url.QueryEscape(name))

	_, err := n.client.Post(ctx, u, nil)
	if err != nil {
		return fmt.Errorf("failed to start network for connection %s: %w", connectionID, err)
	}
	return nil
}

// StopNetwork 停止指定连接的网络
func (n *NetworkClient) StopNetwork(ctx context.Context, connectionID, name string) error {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/network/stop?connection=%s&name=%s", url.QueryEscape(connectionID), url.QueryEscape(name))

	_, err := n.client.Post(ctx, u, nil)
	if err != nil {
		return fmt.Errorf("failed to stop network for connection %s: %w", connectionID, err)
	}
	return nil
}

// GetNetworkXML 获取指定连接网络的 XML 配置
func (n *NetworkClient) GetNetworkXML(ctx context.Context, connectionID, name string) (string, error) {
	// 构建带查询参数的URL
	u := fmt.Sprintf("/api/v1/networks/%s/xml?connection=%s", url.QueryEscape(name), url.QueryEscape(connectionID))

	data, err := n.client.Get(ctx, u)
	if err != nil {
		return "", fmt.Errorf("failed to get network xml for connection %s: %w", connectionID, err)
	}

	return string(data), nil
}
